
# utils/helpers.py - 工具函数
import streamlit as st
import pandas as pd
import json
from datetime import datetime
import os

def check_authentication():
    """检查用户认证状态"""
    if 'authentication_status' not in st.session_state or not st.session_state.authentication_status:
        st.error("⚠️ 请先登录访问此页面!")
        st.info("👆 请使用左侧菜单返回登录页面")
        st.stop()

def get_user_role(username: str) -> str:
    """获取用户角色"""
    admin_users = ['admin']
    return 'admin' if username in admin_users else 'user'

def log_user_activity(username: str, action: str, page: str):
    """记录用户活动日志"""
    log_entry = {
        'timestamp': datetime.now().isoformat(),
        'username': username,
        'action': action,
        'page': page,
        'session_id': st.session_state.get('session_id', 'unknown')
    }
    
    log_file = 'logs/user_activity.json'
    os.makedirs('logs', exist_ok=True)
    
    # 读取现有日志
    if os.path.exists(log_file):
        with open(log_file, 'r', encoding='utf-8') as f:
            try:
                logs = json.load(f)
            except json.JSONDecodeError:
                logs = []
    else:
        logs = []
    
    # 添加新日志
    logs.append(log_entry)
    
    # 保持最近1000条记录
    if len(logs) > 1000:
        logs = logs[-1000:]
    
    # 写入日志文件
    with open(log_file, 'w', encoding='utf-8') as f:
        json.dump(logs, f, ensure_ascii=False, indent=2)

@st.cache_data
def load_user_preferences(username: str) -> dict:
    """加载用户偏好设置"""
    prefs_file = f'config/user_preferences/{username}.json'
    
    default_prefs = {
        'theme': 'light',
        'language': 'zh',
        'sidebar_state': 'expanded',
        'items_per_page': 25,
        'default_page': 'home',
        'notifications': {
            'email': True,
            'push': False,
            'frequency': 'daily'
        }
    }
    
    if os.path.exists(prefs_file):
        with open(prefs_file, 'r', encoding='utf-8') as f:
            try:
                user_prefs = json.load(f)
                # 合并默认设置和用户设置
                return {**default_prefs, **user_prefs}
            except json.JSONDecodeError:
                return default_prefs
    
    return default_prefs

def save_user_preferences(username: str, preferences: dict):
    """保存用户偏好设置"""
    prefs_dir = 'config/user_preferences'
    os.makedirs(prefs_dir, exist_ok=True)
    
    prefs_file = f'{prefs_dir}/{username}.json'
    with open(prefs_file, 'w', encoding='utf-8') as f:
        json.dump(preferences, f, ensure_ascii=False, indent=2)

def format_file_size(size_bytes: int) -> str:
    """格式化文件大小显示"""
    if size_bytes == 0:
        return "0B"
    
    size_names = ["B", "KB", "MB", "GB", "TB"]
    import math
    i = int(math.floor(math.log(size_bytes, 1024)))
    p = math.pow(1024, i)
    s = round(size_bytes / p, 2)
    return f"{s} {size_names[i]}"

def export_data_to_csv(data: pd.DataFrame, filename: str = "export.csv") -> str:
    """导出数据为CSV并返回下载链接"""
    csv_buffer = data.to_csv(index=False)
    return csv_buffer